package com.ly.oa.service.flow.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.hibernate.Session;
import org.jbpm.api.Execution;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.HistoryService;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskService;
import org.jbpm.api.history.HistoryProcessInstance;
import org.jbpm.api.task.Participation;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.env.Environment;
import org.jbpm.pvm.internal.env.EnvironmentFactory;
import org.jbpm.pvm.internal.history.model.HistoryProcessInstanceImpl;
import org.jbpm.pvm.internal.model.Activity;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.Transition;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.task.TaskImpl;

import com.ly.core.jbpm.bean.Node;
import com.ly.core.util.AppUtil;
import com.ly.oa.model.flow.ProDefinition;
import com.ly.oa.model.flow.ProUserAssign;
import com.ly.oa.model.flow.ProcessRun;
import com.ly.oa.model.system.AppUser;
import com.ly.oa.service.flow.JbpmService;
import com.ly.oa.service.flow.ProDefinitionService;
import com.ly.oa.service.flow.ProUserAssignService;
import com.ly.oa.service.flow.ProcessFormService;
import com.ly.oa.service.flow.ProcessRunService;
import com.ly.oa.service.system.UserSubService;

public class JbpmServiceImpl implements JbpmService{
	
	private static final Log logger=LogFactory.getLog(JbpmServiceImpl.class);
	
	@Resource
	private ProcessEngine processEngine;
	
	@Resource
	private RepositoryService repositoryService;
	
	@Resource
	private ExecutionService executionService; 
	
	@Resource
	private ProDefinitionService proDefinitionService;
	
	@Resource
	private TaskService taskService;
	
	@Resource
	private ProUserAssignService proUserAssignService;
	@Resource
	private HistoryService historyService;
	@Resource
	private UserSubService userSubService;
	//TODO 需要去掉该注入方式，把该运行服务转至其他
	@Resource
	private ProcessRunService processRunService;
	
	@Resource
	private ProcessFormService processFormService;
	
//	@Resource
//	private DataSource dataSource;
	
	/**
	 * 发布或更新流程定义
	 * @param proDefinition
	 * @return
	 */
	public ProDefinition saveOrUpdateDeploy(ProDefinition proDefinition){
		//添加流程定义及发布流程至Jbpm流程表中
		if(proDefinition.getDeployId()==null){
			String deployId=repositoryService.createDeployment().addResourceFromString("process.jpdl.xml", proDefinition.getDefXml()).deploy();
		    proDefinition.setDeployId(deployId);
		    proDefinitionService.save(proDefinition);
		    
		}else{
			//先从数据库中移除，保证下次从数据库取出来的是旧的记录而不是Hibernate中的缓存的记录
			proDefinitionService.evict(proDefinition);
			
			ProDefinition proDef=proDefinitionService.get(proDefinition.getDefId());
			//需要比较数据库的xml文件与现在更新的xml文件是否不相同，若不相同则删除原来的发布并布新的流程
			if(!proDef.getDefXml().equals(proDefinition.getDefXml())){
				if(proDef.getDeployId()!=null){
					//不进行删除所有旧流程的东西，保留旧流程运行中的信息。repositoryService.deleteDeploymentCascade(deploymentId)
					repositoryService.deleteDeployment(proDef.getDeployId());
				}
				String deployId=repositoryService.createDeployment().addResourceFromString("process.jpdl.xml", proDefinition.getDefXml()).deploy();
			    
				proDefinition.setDeployId(deployId);
			
			}
			
			proDefinitionService.merge(proDefinition);
		}
		
		return proDefinition;
	}
	
	/**
	 * 按流程定义id取得流程定义的XML
	 * @param defId
	 * @return
	 */
	public String getDefinitionXmlByDefId(Long defId){
		ProDefinition proDefinition=proDefinitionService.get(defId);
		return proDefinition.getDefXml();
	}
	
	/**
	 * 按发布id取得流程定义的XML
	 */
	public String getDefinitionXmlByDpId(String deployId){
		ProDefinition proDefintion=proDefinitionService.getByDeployId(deployId);
		return proDefintion.getDefXml();
	}
	/**
	 * 按流程例id取得流程定义的XML
	 */
	public String getDefinitionXmlByPiId(String piId){
		ProcessInstance pi=executionService.createProcessInstanceQuery().processInstanceId(piId).uniqueResult();
		ProcessDefinition pd=repositoryService.createProcessDefinitionQuery().processDefinitionId(pi.getProcessDefinitionId()).uniqueResult();
		return getDefinitionXmlByDpId(pd.getDeploymentId());
	}
	/**
	 * 取得流程实例
	 * @param piId
	 * @return
	 */
	public ProcessInstance getProcessInstance(String piId){
		ProcessInstance pi=executionService.createProcessInstanceQuery().processInstanceId(piId).uniqueResult();
		return pi;
	}
	
	/**
	 * 通过流程定义取得所有的任务列表
	 * @param defId
	 * @return
	 */
	public List<Node>getTaskNodesByDefId(Long defId){
		ProDefinition proDefinition=proDefinitionService.get(defId);
		return getTaskNodesFromXml(proDefinition.getDefXml(),false);
	}
	
	 /**
     * 从XML文件中取得任务节点名称列表
     * @param xml
     * @param includeStart  是否包括启动节点
     * @return
     */
    private List<Node> getTaskNodesFromXml(String xml,boolean includeStart){
		List<Node> nodes=new ArrayList<Node>();
		try{
			Element root = DocumentHelper.parseText(xml).getRootElement();
			   for (Element elem : (List<Element>) root.elements()) {
		            String type = elem.getQName().getName();
		            if("task".equalsIgnoreCase(type)){
			            if (elem.attribute("name") != null) {
			               Node node=new Node(elem.attribute("name").getValue(),"任务节点");
			               nodes.add(node);
			            }
		            }else if(includeStart && "start".equalsIgnoreCase(type)){
		            	if (elem.attribute("name") != null){
		            		Node node=new Node(elem.attribute("name").getValue(),"开始节点");
				            nodes.add(node);
		            	}
		            }
		       }
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}
		return nodes;
	}
    
	public String startProcess(String deployId, Map variables) {
		ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).uniqueResult();
		//启动工作流
		ProcessInstance pi = executionService.startProcessInstanceById(pd.getId(), variables);
		
		assignTask(pi,pd);
		
		return pi.getId();
	}
	
	public void assignTask(ProcessInstance pi,ProcessDefinition pd){
		
		if(pd==null){
			pd=repositoryService.createProcessDefinitionQuery().processDefinitionId(pi.getProcessDefinitionId()).uniqueResult();
		}
		//取得当前任务的名称，然后根据该任务名称以及流程定义，查看该任务将由哪一个用户或用户组来处理比较合适
		Iterator<String> activityNames=pi.findActiveActivityNames().iterator();
		
		while(activityNames.hasNext()){
			String actName=activityNames.next();
			Task task=taskService.createTaskQuery().processInstanceId(pi.getId()).activityName(actName).uniqueResult();
			if(task!=null){//进行任务的授权用户的操作
				//取得对应的用户
				
				ProUserAssign assign=proUserAssignService.getByDeployIdActivityName(pd.getDeploymentId(), actName);
				
				if(assign!=null){
					if(StringUtils.isNotEmpty(assign.getUserId())){//用户优先处理该任务
						taskService.assignTask(task.getId(), assign.getUserId());
					}
					if(StringUtils.isNotEmpty(assign.getRoleId())){//角色中的人员成为该任务的候选人员
						taskService.addTaskParticipatingGroup(task.getId(), assign.getRoleId(), Participation.CANDIDATE);
					}
				}
			}
		}
	}
	
	/**
	 * 显示某个流程当前任务对应的所有出口
	 * @param piId
	 * @return
	 */
	 public List<Transition> getTransitionsForSignalProcess(String piId) {
		 System.out.println("piId="+piId);
	        ProcessInstance pi = executionService.findProcessInstanceById(piId);
	        EnvironmentFactory environmentFactory = (EnvironmentFactory) processEngine;
	        Environment env = environmentFactory.openEnvironment();

	        try {
	            ExecutionImpl executionImpl = (ExecutionImpl) pi;
	            Activity activity = executionImpl.getActivity();

	            return activity.getOutgoingTransitions();
	        } finally {
	            env.close();
	        }
	    }
	 
	 /*
	  * (non-Javadoc)
	  * @see com.ly.oa.service.flow.JbpmService#getProcessDefintionXMLByPiId(java.lang.String)
	  */
	 public String getProcessDefintionXMLByPiId(String piId){
		 ProcessRun processRun=processRunService.getByPiId(piId);
		 return processRun.getProDefinition().getDefXml();
	 }
	 
	 /**
	  * 取得某流程实例对应的任务列表
	  * @param piId
	  * @return
	  */
	 public List<Task> getTasksByPiId(String piId){
		 List<Task> taskList=taskService.createTaskQuery().processInstanceId(piId).list();
		 return taskList;
	 }
	    
    /**
	 * 取到节点类型
	 * @param xml
	 * @param nodeName
	 * @return
	 */
	public String getNodeType(String xml,String nodeName){
		String type="";
		try{
			Element root = DocumentHelper.parseText(xml).getRootElement();
			for (Element elem : (List<Element>) root.elements()){
				if(elem.attribute("name")!=null){
					String value=elem.attributeValue("name");
					if(value.equals(nodeName)){
						type = elem.getQName().getName();
						return type;
					}
				}
			}
		}catch(Exception ex){
			logger.info(ex.getMessage());
		}
		return type;
	}
	
	/**
	 * 完成任务
	 * @param taskId
	 * @param transitionName
	 * @param variables
	 */
	public void completeTask(String taskId,String transitionName,Map variables){
		Task task=taskService.getTask(taskId);
		ProcessInstance pi=executionService.createProcessInstanceQuery().processInstanceId(task.getExecutionId()).uniqueResult();
		//完成任务
		taskService.setVariables(taskId, variables);
	    taskService.completeTask(taskId, transitionName);
	    
	    //为下一任务授权
	    assignTask(pi, null);
	}
	public void completeTask(String taskId, String transitionName, String destName, Map variables)
	  {
	    TaskImpl taskImpl = (TaskImpl)this.taskService.getTask(taskId);

	    String sourceName = taskImpl.getName();

	    TaskImpl superTask = taskImpl.getSuperTask();

	    ProcessDefinitionImpl pd = (ProcessDefinitionImpl)getProcessDefinitionByTaskId(taskId);
	    ProcessInstance pi = null;
	    String executionId = null;

	    boolean isTransitionExist = false;

	    List<Transition> trans = getTransitionsByTaskId(taskId);
	    for (Transition tran : trans) {
	      if (tran.getDestination().getName().equals(destName)) {
	        isTransitionExist = true;
	        break;
	      }
	    }

	    if (!isTransitionExist) {
	      addOutTransition(pd, sourceName, destName);
	    }

	    if (superTask != null) {
	      pi = superTask.getProcessInstance();
	      executionId = superTask.getExecutionId();
	      if (logger.isDebugEnabled()) {
	        logger.debug("Super task is not null, task name is:" + superTask.getActivityName());
	      }

	      if (superTask.getSubTasks() != null)
	      {
	        if (superTask.getSubTasks().size() == 1) {
	          this.taskService.setVariables(taskId, variables);
	          clearSession();

	          this.taskService.completeTask(taskId);

	          this.taskService.completeTask(superTask.getId(), transitionName);
	        } else {
	          this.taskService.setVariables(taskId, variables);
	          clearSession();
	          this.taskService.completeTask(taskId);

	          return;
	        }
	      }
	    } else {
	      pi = taskImpl.getProcessInstance();
	      executionId = taskImpl.getExecutionId();
	      this.taskService.setVariables(taskId, variables);
	      flush();
	      this.taskService.completeTask(taskId, transitionName);
	    }

	    if (!isTransitionExist) {
	      removeOutTransition(pd, sourceName, destName);
	    }

	    boolean isEndProcess = isProcessInstanceEnd(executionId);
	    if (isEndProcess) {
	      ProcessRun processRun = this.processRunService.getByPiId(executionId);
	      if (processRun != null) {
	        processRun.setPiId(null);
	        processRun.setRunStatus(ProcessRun.RUN_STATUS_FINISHED);
	        this.processRunService.save(processRun);
	      }
	      return;
	    }

	    String signUserIds = (String)variables.get("signUserIds");

	    if ((destName != null) && (StringUtils.isNotEmpty(signUserIds)))
	    {
	      List<Task> newTasks = getTasksByPiId(pi.getId());
	      for (Task nTask : newTasks) {
	        if (destName.equals(nTask.getName())) {
	          newTask(nTask.getId(), signUserIds);
	          break;
	        }
	      }
	      return;
	    }
	    destName = null;

	    String assignId = (String)variables.get("flowAssignId");

	    assignTask(pi, null, assignId, destName);
	  }
	public void assignTask(ProcessInstance pi, ProcessDefinition pd, String assignId, String taskName)
	  {
	    if (pd == null) {
	      pd = this.repositoryService.createProcessDefinitionQuery().processDefinitionId(pi.getProcessDefinitionId()).uniqueResult();
	    }

	    List<Task> taskList = null;

	    if (StringUtils.isNotEmpty(taskName)) {
	      taskList = this.taskService.createTaskQuery().processInstanceId(pi.getId()).activityName(taskName).list();
	    }

	    if ((taskList == null) || (taskList.size() == 0)) {
	      taskList = getTasksByPiId(pi.getId());
	    }

	    for (Task task : taskList)
	    {
	      if (StringUtils.isNotEmpty(assignId)) {
	        this.taskService.assignTask(task.getId(), assignId);
	      }
	      else
	      {
	        ProUserAssign assign = this.proUserAssignService.getByDeployIdActivityName(pd.getDeploymentId(), task.getActivityName());

	        if (assign != null)
	        {
	          if ("__start".equals(assign.getUserId()))
	          {
	            AppUser flowStartUser = (AppUser)this.executionService.getVariable(pi.getId(), "flowStartUser");
	            if (flowStartUser != null)
	              this.taskService.assignTask(task.getId(), flowStartUser.getUserId().toString());
	          }
	          else
	          {
	            StringBuffer upIds;
	            Object localObject;
	            Long userId;
	            if ("__super".equals(assign.getUserId())) {
	              AppUser flowStartUser = (AppUser)this.executionService.getVariable(pi.getId(), "flowStartUser");

	              if (flowStartUser != null) {
	                List superUserIds = this.userSubService.upUser(flowStartUser.getUserId());
	                upIds = new StringBuffer();
	                for (localObject = superUserIds.iterator(); ((Iterator)localObject).hasNext(); )
	                { 	userId = (Long)((Iterator)localObject).next();
	                  	upIds.append(userId).append(","); 
	                 }

	                if (superUserIds.size() > 0)
	                  upIds.deleteCharAt(upIds.length() - 1);
	                else {
	                  upIds.append(flowStartUser.getUserId());
	                }
	                this.taskService.addTaskParticipatingUser(task.getId(), upIds.toString(), "candidate");
	              }
	            } else if (StringUtils.isNotEmpty(assign.getUserId())) {
	              String[] userIds = assign.getUserId().split("[,]");

	              if ((userIds != null) && (userIds.length > 1)) {
	            	 // userId = (localObject = userIds).length; 
	            	  for ( int u=0;u<userIds.length;u++)//upIds = 0; upIds < userId; ++upIds) 
	            	  { 
	            		  String uId =userIds[u];//userId[u];//localObject[upIds];
	            		  this.taskService.addTaskParticipatingUser(task.getId(), uId, "candidate");
	                  }
	              }
	              else {
	                this.taskService.assignTask(task.getId(), assign.getUserId());
	              }
	            }
	          }
	          if (StringUtils.isNotEmpty(assign.getRoleId()))
	            this.taskService.addTaskParticipatingGroup(task.getId(), assign.getRoleId(), "candidate");
	        }
	        else
	        {
	          AppUser flowStartUser = (AppUser)this.executionService.getVariable(pi.getId(), "flowStartUser");
	          if (flowStartUser != null)
	            this.taskService.assignTask(task.getId(), flowStartUser.getUserId().toString());
	        }
	      }
	    }
	  }


	/**
     * 执行下一步的流程，对于非任务节点
     * @param id processInstanceId
     * @param transitionName
     * @param variables
     */
    public void signalProcess(String executionId, String transitionName,
        Map<String, Object> variables) {
       
        executionService.setVariables(executionId,variables);
        //executionService.signalExecutionById(id);
        executionService.signalExecutionById(executionId,transitionName);
    }
    
    
    public void endProcessInstance(String piId) {
        ExecutionService executionService = processEngine
            .getExecutionService();
        executionService.endProcessInstance(piId,Execution.STATE_ENDED);
    }
    public String getStartNodeName(ProDefinition proDefinition)
    {
      String filePath = AppUtil.getAppAbsolutePath() + "/WEB-INF/FlowForm/" + proDefinition.getName() + "/开始.vm";

      File file = new File(filePath);

      if (file.exists())
        return "开始";
      try
      {
        Element root = DocumentHelper.parseText(proDefinition.getDefXml()).getRootElement();
        for (Element elem : (List<Element>)root.elements()) {
          String tagName = elem.getName();
          if ("start".equals(tagName)) {
            Attribute nameAttr = elem.attribute("name");
            if (nameAttr != null)
              return nameAttr.getValue();
          }
        }
      }
      catch (Exception ex)
      {
        logger.error(ex.getMessage());
      }
      return "开始";
    }
    public ProcessInstance getProcessInstanceByTaskId(String taskId) {
        TaskImpl taskImpl = (TaskImpl)this.taskService.getTask(taskId.toString());
        if (taskImpl.getSuperTask() != null) {
          taskImpl = taskImpl.getSuperTask();
        }
        return taskImpl.getProcessInstance();
      }

    public List<Transition> getTransitionsByTaskId(String taskId)
    {
      TaskImpl task = (TaskImpl)this.taskService.getTask(taskId);
      if (task.getSuperTask() != null) {
        task = task.getSuperTask();
      }
      EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
      Environment env = environmentFactory.openEnvironment();
      try {
        ProcessDefinitionImpl pd = task.getProcessInstance().getProcessDefinition();
        ActivityImpl activityFind = pd.findActivity(task.getActivityName());

        if (activityFind != null)
          return activityFind.getOutgoingTransitions();
      }
      finally {
        env.close();
      }
      return new ArrayList();
    }
    public List<Transition> getFreeTransitionsByTaskId(String taskId)
    {
      TaskImpl task = (TaskImpl)this.taskService.getTask(taskId);

      List outTrans = new ArrayList();

      if (task.getSuperTask() != null) {
        task = task.getSuperTask();
      }
      EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
      Environment env = null;
      try {
        env = environmentFactory.openEnvironment();
        ProcessDefinitionImpl pd = task.getProcessInstance().getProcessDefinition();
        ActivityImpl curActivity = pd.findActivity(task.getActivityName());

        List<Node> allTaskNodes = getJumpNodesByDeployId(pd.getDeploymentId());

        for (Node taskNode : allTaskNodes) {
          if (taskNode.getName().equals(task.getActivityName()))
            continue;
          TransitionImpl transition = curActivity.createOutgoingTransition();

          transition.setName("to" + taskNode.getName());
          transition.setDestination(pd.findActivity(taskNode.getName()));

          curActivity.getOutgoingTransitions().remove(transition);

          outTrans.add(transition);
        }
      }
      catch (Exception ex) {
        logger.error(ex.getMessage());
      } finally {
        if (env != null) env.close();
      }

      return outTrans;
    }
    public List<Node> getJumpNodesByDeployId(String deployId)
    {
      ProDefinition proDefinition = this.proDefinitionService.getByDeployId(deployId);
      return getTaskNodesFromXml(proDefinition.getDefXml(), false, true);
    }
    private List<Node> getTaskNodesFromXml(String xml, boolean includeStart, boolean includeEnd)
    {
      List nodes = new ArrayList();
      try {
        Element root = DocumentHelper.parseText(xml).getRootElement();
        for (Element elem : (List<Element>)root.elements()) {
          String type = elem.getQName().getName();
          if ("task".equalsIgnoreCase(type)) {
            if (elem.attribute("name") != null) {
              Node node = new Node(elem.attribute("name").getValue(), "任务节点");
              nodes.add(node);
            }
          } else if ((includeStart) && ("start".equalsIgnoreCase(type))) {
            if (elem.attribute("name") != null) {
              Node node = new Node(elem.attribute("name").getValue(), "开始节点");
              nodes.add(node);
            }
          } else if ((includeEnd) && (type.startsWith("end"))) {
            Node node = new Node(elem.attribute("name").getValue(), "结束节点");
            nodes.add(node);
          }
        }
      } catch (Exception ex) {
        logger.error(ex.getMessage());
      }
      return nodes;
    }
    protected void clearSession() {
        EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
        Environment env = environmentFactory.openEnvironment();
        try {
          Session session = (Session)env.get(Session.class);
          session.clear();
        } finally {
          env.close();
        }
      }
    public ProcessDefinition getProcessDefinitionByTaskId(String taskId)
    {
      TaskImpl task = (TaskImpl)this.taskService.getTask(taskId);
      ProcessInstance pi = null;
      if (task.getSuperTask() != null)
        pi = task.getSuperTask().getProcessInstance();
      else {
        pi = task.getProcessInstance();
      }
      ProcessDefinition pd = this.repositoryService.createProcessDefinitionQuery().processDefinitionId(pi.getProcessDefinitionId()).uniqueResult();
      return pd;
    }
    public void addOutTransition(ProcessDefinitionImpl pd, String sourceName, String destName)
    {
      EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
      Environment env = null;
      try {
        env = environmentFactory.openEnvironment();

        ActivityImpl sourceActivity = pd.findActivity(sourceName);

        ActivityImpl destActivity = pd.findActivity(destName);

        TransitionImpl transition = sourceActivity.createOutgoingTransition();
        transition.setName("to" + destName);
        transition.setDestination(destActivity);

        sourceActivity.addOutgoingTransition(transition);
      }
      catch (Exception ex) {
        logger.error(ex.getMessage());
      } finally {
        if (env != null) env.close();
      }
    }
    protected void flush() {
        EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
        Environment env = environmentFactory.openEnvironment();
        try {
          Session session = (Session)env.get(Session.class);
          session.flush();
        } finally {
          env.close();
        }
      }
    public void removeOutTransition(ProcessDefinitionImpl pd, String sourceName, String destName)
    {
      EnvironmentFactory environmentFactory = (EnvironmentFactory)this.processEngine;
      Environment env = null;
      try {
        env = environmentFactory.openEnvironment();

        ActivityImpl sourceActivity = pd.findActivity(sourceName);

        List<Transition> trans = sourceActivity.getOutgoingTransitions();
        for (Transition tran : trans) {
          if (destName.equals(tran.getDestination().getName()))
            trans.remove(tran);
        }
      }
      catch (Exception ex)
      {
        logger.error(ex.getMessage());
      } finally {
        if (env != null) env.close();
      }
    }
    protected boolean isProcessInstanceEnd(String executionId)
    {
      HistoryProcessInstance hpi = this.historyService.createHistoryProcessInstanceQuery().processInstanceId(executionId).uniqueResult();
      if (hpi != null) {
        String endActivityName = ((HistoryProcessInstanceImpl)hpi).getEndActivityName();
        if (endActivityName != null) {
          return true;
        }
      }
      return false;
    }
    public void newTask(String parentTaskId, String assignIds)
    {
//      TaskServiceImpl taskServiceImpl = (TaskServiceImpl)this.taskService;
      Task parentTask = this.taskService.getTask(parentTaskId);

      if (assignIds != null) {
        String[] userIds = assignIds.split("[,]");
        for (int i = 0; i < userIds.length; ++i) {
          TaskImpl task = (TaskImpl)this.taskService.newTask(parentTaskId);
          task.setAssignee(userIds[i]);
          task.setName(parentTask.getName() + "-" + (i + 1));
          task.setActivityName(parentTask.getName());
          task.setDescription(parentTask.getDescription());
          this.taskService.saveTask(task);
        }
      }
    }
}
